package com.xxh.food.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxh.food.common.entity.User;
import com.xxh.food.common.param.UserPARAM;
import com.xxh.food.mapper.UserMapper;
import com.xxh.food.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService{

    @Resource
    private UserMapper userMapper;

    @Override
    public User login(String username,String password) {
        return lambdaQuery().eq(User::getUsername,username)
                .eq(User::getPassword,password)
                .one();
    }

    @Override
    public User adminLogin(String username,String password) {
        return lambdaQuery().eq(User::getUsername,username)
                .eq(User::getPassword,password)
                .eq(User::getRole,1)
                .one();
    }

    @Override
    public User findUserByUsername(String username) {
        return lambdaQuery().eq(User::getUsername,username)
                .one();
    }

    @Override
    public Page<User> findUserByPage(Integer pageNum, Integer pageSize, UserPARAM userPARAM) {
        Page<User> page = new Page(pageNum, pageSize);
        QueryWrapper<User> qw = new QueryWrapper<>();

        if(userPARAM == null){

            return userMapper.selectPage(page, qw);
        }

        if(StringUtils.isNotEmpty(userPARAM.getId())){
            qw.like("id",userPARAM.getId());
        }
        if(StringUtils.isNotEmpty(userPARAM.getUsername())){
            qw.like("username",userPARAM.getUsername());
        }
        if(StringUtils.isNotEmpty(userPARAM.getPassword())){
            qw.like("password",userPARAM.getPassword());
        }
        if(StringUtils.isNotEmpty(userPARAM.getTelephone())){
            qw.like("telephone",userPARAM.getTelephone());
        }
        if(StringUtils.isNotEmpty(userPARAM.getMail())){
            qw.like("mail",userPARAM.getMail());
        }
        if(StringUtils.isNotEmpty(userPARAM.getRole())){
            qw.like("role",userPARAM.getRole());
        }


        return userMapper.selectPage(page,qw);
    }

    @Override
    public int userNum() {
        QueryWrapper<User> qw = new QueryWrapper<>();
        return Math.toIntExact(userMapper.selectCount(qw));
    }
}
